<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="code === 1">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail markdown-body" v-if="code === 2">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ articelInfo.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="articelInfo.aut_photo"
          />
          <div slot="title" class="user-name">{{ articelInfo.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ articelInfo.pubdate | relativeTime }}
          </div>

          <!----------------- 关注组件 S --------------->
          <!-- <followUser 
         :author-id="articelInfo.aut_id"
          :value="articelInfo.is_followed"
         @input="articelInfo.is_followed=$event"
         ></followUser> -->

         <!-- 场景： 子组件既要用父组件传递进入的数据，又要改变这个数据 关注 点赞 收藏 弹出框。。。 -->
         <!-- v-model 组件 是value属性和input事件的语法糖(简写) -->
         <!-- 一个组件只能有一个v-model -->
          <followUser
            :author-id="articelInfo.aut_id"
            v-model="articelInfo.is_followed"
          ></followUser>

          <!---------------- 关注组件 E --------------->
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
          class="article-content"
          ref="content"
          v-html="articelInfo.content"
        ></div>
        <van-divider>正文结束</van-divider>
        <!-- --------------------文章评论列表组件------------------------------- -->
         <comment-list 
         @open-reply="openReply"
         :sourceId='articleId'
         @update-total="commentTotalCount=$event"
         :list="commentListDate"
         ></comment-list>
        <!-- ----------------------文章评论列表组件----------------------------- -->



        <!-- ---------------------对文章进行评论组件----------------------------- -->
        <van-popup v-model="isPostShow" position="bottom">
          <comment-post 
          :target='articleId' 
          @close='isPostShow=false'
           @update-list="updateList"></comment-post>
        </van-popup>
        <!-- ---------------------对文章进行评论组件----------------------------- -->


        <!-- ---------------------评论回复内容组件----------------------------- -->
       <van-popup v-model="isReplyShow" position="bottom" style="height: 100%;">
         <commentReply 
         @close='isReplyShow=false'
         v-if="isReplyShow"
          :curComment="clickCurrentComment"></commentReply>
       </van-popup>
        <!-- ---------------------评论回复内容组件----------------------------- -->

        <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button class="comment-btn" type="default" round size="small" @click="isPostShow=true"
            >写评论</van-button
          >
          <van-icon name="comment-o" :badge="commentTotalCount" color="#777" />
          <!-- 文章收藏组件 -->
           <collectArticle  
           :articleId='articleId'
           v-model="articelInfo.is_collected"></collectArticle>
           <!-- 文章收藏组件 -->

          <!-- 文章点赞组件 -->
          <!-- <zanArticle 
          :is-zan="articelInfo.attitude" 
          :articleId="articleId" 
          @update-zan="articelInfo.attitude=$event"> </zanArticle> -->

          <zanArticle 
          :is-zan.sync="articelInfo.attitude" 
          :articleId="articleId" > </zanArticle>
          <!-- .sync 修饰符的意思是实现父子组件双向绑定, 作用和v-model完全一样 -->
          <!-- 一个组件只能有1个v-model 可以有很多个.sync修饰符 -->
          <!-- 本质是一个语法糖(简写) -->
          <!-- 子组件: props:['s属性名'] this.$emit('unpdate:属性名',新值) -->
          <!-- 父组件: <组件:属性名='变量' @update:属性名="变量=$event"  />
              简写:<组件:属性名.sync='变量'  />
          -->

          <!-- 文章点赞组件 -->
          <van-icon name="share" color="#777777"></van-icon>
        </div>
        <!-- /底部区域 -->
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-if="code === 3">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-if="code === 4">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="initCate">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>
  </div>
</template>

<script>
// $route.params.articleId 读取文章ID数据
import { getArticleDetail } from "@/api/article";
// 导入第三方的文章正文样式文件
import "./github-markdown.css";
// 导入图片预览函数
import { ImagePreview } from "vant";
// ImagePreview ({ images:[图片地址数组],startPosition图片预览起始位置索引})

// import { addFollow, deleteFollow } from "@/api/user";

import followUser from "@/components/follow-user";
import collectArticle from '@/components/collect-article'
import zanArticle from '@/components/zan-article'
import commentList from '@/views/article/components/comment-list'
import commentPost from '@/views/article/components/comment-post'
import commentReply from '@/views/article/comment-reply'
export default {
  name: "ArticleIndex",
  components: { followUser,collectArticle,zanArticle,commentList,commentPost,commentReply },
  props: {
    // 使用props获取动态路由的数据 文章id
    articleId: {
      type: [Number, String],
      required: true,
    },
  },
  // 祖先与后代通信 提供数据
  provide() {
      return {
      articleId:this.articleId
      }
  },
  data() {
    return {
      articelInfo: {}, //文章详情列表
      code: 1, // 1 处于加载中 2 加载成功 3 404错误 4 服务器异常
      // isLoading: false, //是否处于关注加载中
      commentTotalCount:'', //文章评论的总数量
      isPostShow:false, // 
      commentListDate:[], //文章评论列表
      isReplyShow:false,
      clickCurrentComment:{} //点击的评论项信息
    };
  },
  computed: {},
  watch: {},
  created() {
    this.initCate();
  },
  mounted() {},
  methods: {
    async initCate() {
      try {
        // 为了重新加载 一开始需要加载中
        this.code = 1;
        let { data } = await getArticleDetail(this.articleId);
        console.log(data);
        this.articelInfo = data.data;
        this.code = 2;
        // $nextTick 是等到DOM渲染完成之后再执行相应代码逻辑
        // 页面的渲染是耗时的 是异步的任务
        // 不能直接在下方去读取节点内容
        // console.log(this.$refs.content);  这种是读取不到的 undefied
        this.$nextTick(() => {
          this.bindImgClick();
          // // 1 获取容器的原生DOM节点
          // console.log(this.$refs.content);
          // // 2 获取文章正文容器内的所有图片节点
          //    const imgNode=this.$refs.content.querySelectorAll('img')
          //    console.log(imgNode);
          // //    3 遍历取出图片地址和绑定点击事件
          // const imgUrls=[]
          // imgNode.forEach((img,idx) => {
          //     imgUrls.push(img.src)
          //     img.onclick=()=> {
          //         ImagePreview({
          //             images:imgUrls,
          //             startPosition:idx
          //         })
          //     }
          // });
          // console.log(imgUrls);
        });
      } catch (error) {
        console.dir(error);
        if (error && error.response && error.response.status === 404)
          this.code = 3;
        this.code = 4;
      }
    },
    bindImgClick() {
      // 1 获取容器的原生DOM节点
      console.log(this.$refs.content);
      // 2 获取文章正文容器内的所有图片节点
      const imgNode = this.$refs.content.querySelectorAll("img");
      console.log(imgNode);
      //    3 遍历取出图片地址和绑定点击事件
      const imgUrls = [];
      imgNode.forEach((img, idx) => {
        imgUrls.push(img.src);
        img.onclick = () => {
          ImagePreview({
            images: imgUrls,
            startPosition: idx,
          });
        };
      });
      // console.log(imgUrls);
    },
    // 将数据放到评论列表顶部
    updateList(val) {
      console.log(val);
      this.commentListDate.unshift(val.new_obj)
    },
    // 打开回复组件
    openReply(val) {
      console.log(val);
      // 把信息给弹出之后的评论项信息
      this.clickCurrentComment=val
      // 打开弹出层
      this.isReplyShow=true
    }
  },
};
</script>

<style scoped lang="less">
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    z-index: 1;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
